using System.IO;
using log4net;
using SQLRunnerLib.RunnableItems;
using SQLServices.RunnableItems;

namespace SQLRunner.gui
{
    public class ScriptsController
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(ScriptsController).FullName);

        private IScriptsView scriptsView;
        private ScriptsModel scriptsModel;

        #region Constructors


        #endregion

        #region IScriptsController Members

        public IScriptsView ScriptsView
        {
            get { return scriptsView; }
            set 
            {
                scriptsView = value;
                scriptsView.Controller = this;
            }
        }

        public ScriptsModel ScriptsModel
        {
            get { return scriptsModel; }
            set { scriptsModel = value; }
        }

        public void AddNewFolder(DirectoryInfo directory)
        {
            if (directory.Exists) scriptsModel.AddDir(directory);
        }

        public void DisplayView()
        {
            scriptsView.DisplayView();
        }

        public void MoveItemUp(string node)
        {
            IProjectItem item = scriptsModel.ProjectMgr.GetProjectItem(node);
            if (item == null) return;
            ProjectFolder parent = item.Parent as ProjectFolder;
            if (parent == null) return;
            int index = parent.Children.IndexOf(item);
            if (index == 0) return;            
            parent.Children.Remove(item);
            parent.Children.Insert(index - 1, item);
        }

        public void MoveItemDown(string node)
        {
            IProjectItem item = scriptsModel.ProjectMgr.GetProjectItem(node);
            if (item == null) return;
            ProjectFolder parent = item.Parent as ProjectFolder;
            if (parent == null) return;
            int index = parent.Children.IndexOf(item);
            if (parent.Children.Count == (index + 1)) return;
         
            parent.Children.Remove(item);
            parent.Children.Insert(index + 1, item);
        }

        public void NodeChecked(string node, bool value)
        {
            IProjectItem item = scriptsModel.ProjectMgr.GetProjectItem(node);
            if (item == null) return;
            item.Selected = value;
        }

        public void AddNewFile()
        {
            throw new System.NotImplementedException();
        }

        #endregion
    }
}
